package com.qianfeng.smartdevice.event.listeners;

import com.qianfeng.smartdevice.event.DevicePowerEvent;
import com.qianfeng.smartdevice.pojo.SysDevice;
import com.qianfeng.smartdevice.service.SysDeviceService;
import com.qianfeng.smartdevice.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by wenka on 2022/3/27 13:58
 *
 * @author wenkaixin
 * @version 1.0
 * @since 1.0
 */
@Component
public class DevicePowerListener {
    private SysDeviceService sysDeviceService;

    @Autowired
    public void setSysDeviceService(SysDeviceService sysDeviceService) {
        this.sysDeviceService = sysDeviceService;
    }
    @EventListener
    @Async
    public void onEvent(DevicePowerEvent event){
        String ip = event.getIp();
        String deviceId = event.getDeviceId();
        //获取地区
        String locationByIp = RequestUtil.getLocationByIp(ip);
        SysDevice sysDevice = new SysDevice();
        sysDevice.setDeviceId(deviceId);
        switch (event.getDeviceStatus()){
            case ONLINE:
                sysDevice.setConnectTime(new Date());
                sysDevice.setCurrentConnectIp(ip);
                sysDevice.setConnectLocation(locationByIp);
                //设置为在线
                sysDevice.setIsOnline(1L);
                break;
            case OFFLINE:
                sysDevice.setLostConnectTime(new Date());
                //设置为离线
                sysDevice.setIsOnline(2L);
                break;
        }
        //更新数据
        sysDeviceService.updateDeviceById(sysDevice);
    }
}
